﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using Kugar.Core.ExtMethod;
using Kugar.UI.Web.AdminLTE.Helpers;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace Kugar.UI.Web.AdminLTE.PageControls.PageForms
{
    public abstract class PageForm_FieldBase : ControlBase
    {
        private PageForm_Form _form = null;
        //private string _id = "";
        internal string _label = "";
        internal int _labelWidth = 0;
        internal string _controlWidth = "";
        //protected string _errorMsg = "";
        //protected bool _hasError = false;
        //internal bool _required = false;
        internal string _tips = "";
        internal bool _isHide = false;

        public PageForm_FieldBase(PageForm_Form form, ViewContext viewContext) : base(viewContext)
        {
            _form = form;
            this.Css("form-group webui-form_formfield");

            var defaultWidth = ((int?)ViewContext.ViewData["DefaultLabelWidth"])??2;

            this._labelWidth = defaultWidth;

            this._controlWidth = (string)ViewContext.ViewData["DefaultControlWidth"];
        }

        protected PageForm_Form Form => _form;

        protected virtual void BeforeRender(TextWriter writer) { }

        protected virtual void AfterRender(TextWriter writer) { }

        protected virtual void BeforeRenderContent(TextWriter writer) { }

        protected virtual void AfterRenderContent(TextWriter writer) { }

        public override HtmlString Render()
        {
            //_hasError = HasError;

            if (_isHide)
            {
                return HtmlString.Empty;
            }

            if (HasError)
            {
                this.Css("has-error");
            }

            BeforeRender(ViewContext.Writer);

            if (_withOuterBorder)
            {
                ViewContext.Writer.WriteLine($"<div class=\"{_outerBorderCss}\">");
            }

            if (Attributes.GetValue("class").Contains("fullrow",true))
            {
                ViewContext.Writer.WriteLine("<div class=\"clearfix\"></div>");
            }

            ViewContext.Writer.WriteLine($"<div {Attributes}>");

            if (_labelWidth != 0 && !string.IsNullOrEmpty(_label))
            {
                ViewContext.Writer.WriteLine($"<label class=\"col-sm-{_labelWidth} control-label\">");

                RenderLabel(ViewContext.Writer);

                ViewContext.Writer.WriteLine("</label>");
            }

            ViewContext.Writer.WriteLine($"<div class=\"col-sm-{(string.IsNullOrEmpty(_label) ? 12 : 12 - _labelWidth)} control-content\">");

            ViewContext.Writer.WriteLine($"<div class=\"input-group row\" style=\"{(string.IsNullOrWhiteSpace(_controlWidth) ? "" : $"width:{_controlWidth} !important;")}\">");

            BeforeRenderContent(ViewContext.Writer);

            RenderContent(ViewContext.Writer);

            AfterRenderContent(ViewContext.Writer);


            //if (_required)
            //{
            //    ViewContext.Writer.WriteLine("<span class=\"input-group-addon required\" ><i class=\"fa fa-star\"></i></span>");
            //    ViewContext.Writer.WriteLine("<div class=\"clearfix\"></div>");
            //}

            ViewContext.Writer.WriteLine("<div class=\"clearfix\"></div>");

            ViewContext.Writer.WriteLine("</div>");


            if (!string.IsNullOrWhiteSpace(_tips))
            {
                ViewContext.Writer.WriteLine($"<span class=\"input-group-addon tips\">{_tips}</span>");
                ViewContext.Writer.WriteLine("<div class=\"clearfix\"></div>");
            }

            //if (HasError)
            {
                ViewContext.Writer.WriteLine($"<span class=\"field-errormsg help-block\">{ErrorMessage}</span>");
            }

            ViewContext.Writer.WriteLine("<div class=\"clearfix\"></div>");

            ViewContext.Writer.WriteLine("</div> <!-- end control-content -->");

            ViewContext.Writer.WriteLine("<div class=\"clearfix\"></div>");

            ViewContext.Writer.WriteLine("</div> <!--end webui-form_formfield -->");

            if (_withOuterBorder)
            {
                ViewContext.Writer.WriteLine($"</div> <!-- outer border -->");
            }

            AfterRender(ViewContext.Writer);
            

            return HtmlString.Empty;
        }

        protected virtual void RenderLabel(TextWriter writer)
        {
            writer.WriteLine(_label);
        }

        protected abstract void RenderContent(TextWriter writer);

        protected virtual bool HasError { get; }

        protected virtual string ErrorMessage { get; }

        protected string GetErrorMessageByNames(params string[] names)
        {
            var sb = new StringBuilder();

            foreach (var name in names)
            {
                if (string.IsNullOrWhiteSpace(name))
                {
                    continue;
                }

                if (ViewContext.ModelState.TryGetValue(name, out var error))
                {
                    foreach (var ex in error.Errors)
                    {
                        sb.Append(ex.ErrorMessage);
                        sb.Append('|');
                    }
                }
            }

            if (sb.Length <= 0)
            {
                return string.Empty;
            }

            if (sb[sb.Length - 1] == '|')
            {
                return sb.ToString(0, sb.Length - 1);
            }

            return sb.ToString();
        }

        protected bool IsHasErrorByNames(params string[] names)
        {
            foreach (var name in names)
            {
                if ( ViewContext.ModelState.TryGetValue(name,out var error) && error.Errors.HasData())
                {
                    return true;
                }
            }

            return false;
        }
    }

    public abstract class PageForm_InputFieldBase : PageForm_FieldBase
    {
        internal bool _isRequired = false;

        protected PageForm_InputFieldBase(PageForm_Form form, ViewContext viewContext) : base(form, viewContext)
        {
        }

        protected override void RenderLabel(TextWriter writer)
        {
            this.Css("webui-form_requiredfield");

            writer.WriteLine($"{(_isRequired ? "<i class=\"fa fa-fw fa-asterisk requiredfield_label\"></i>" : "")}{HttpUtility.HtmlEncode(_label)}");
        }
    }

    public abstract class PageForm_SingleInputFieldBase : PageForm_InputFieldBase
    {
        internal string _name = "";

        protected PageForm_SingleInputFieldBase(PageForm_Form form, ViewContext viewContext) : base(form, viewContext)
        {
        }

        public string GetFieldName => _name;

        protected override string ErrorMessage
        {
            get
            {
                return GetErrorMessageByNames(_name);

                //if (ViewContext.ModelState.TryGetValue(_name, out var error)) // ModelMetadata.FromStringExpression(_name, ViewContext.ViewData);
                //{
                //    return error.Errors.Select(x => x.ErrorMessage).JoinToString('|');
                //}
                //else
                //{
                //    return "";
                //}
            }
        }

        protected override bool HasError
        {
            get
            {
                return IsHasErrorByNames(_name);

                //if (ViewContext.ViewData.ModelState.TryGetValue(_name,out var errors))
                //{
                //    return errors.Errors.HasData();
                //}

                //return false;
            }
        }


    }
}
